import fs from 'fs'
import marked from 'marked'

const mdToJs = str => {
    const content = JSON.stringify(marked(str))
    return `export default ${content}`
}

const mdPlugin = ({
    root, // project root directory, absolute path
    app, // Koa app instance
    server, // raw http server instance
    watcher // chokidar file watcher instance
  }) => {
    app.use(async (ctx, next) => {
        if (ctx.path.endsWith('.md')) {
            const totalPath = root.concat(ctx.path).replace('@', 'src')
            fs.readFile(totalPath, 'utf8', (err, data) => {
                if(err) throw err
                ctx.type = 'js'
                ctx.body = mdToJs(data)
                console.log(mdToJs(data))
            })
        }
        await next()
    })
  }
const mdTransform = {
    test: ctx => ctx.path.endsWith('.md') ,
    transform: ({ code }) => mdToJs(code)
}

export { mdPlugin, mdTransform }